package com.sxt.demo.djiapplication.dao

import org.greenrobot.greendao.AbstractDao

/**
 * T: 数据类型
 * E: id类型 use Void if entity does not have exactly one PK
 */
@Suppress("unused")
interface IService<T : AbstractDao<DATA, E>, E, DATA> {

    val daoSession: DaoSession

    val dao: T

    fun add(data: DATA): Long {
        return try {
            dao.insert((data))
        } catch (e: Exception) {
            0
        }
    }

    fun queryAll(): Pair<List<DATA>, Boolean> {
        return try {
            Pair(dao.loadAll(), true)
        } catch (e: Exception) {
            Pair(emptyList(), false)
        }
    }

    fun queryByOffset(
        page: Int = 1,
        limit: Int = 10,
        desc: Boolean = false
    ): Pair<List<DATA>, Boolean> {
        val query = dao.queryBuilder()
            .offset((page * limit) - limit)
            .limit(limit)
        if (desc) {
            query.orderDesc(dao.pkProperty)
        }
        return try {
            Pair(query.list(), true)
        } catch (e: Exception) {
            Pair(emptyList(), false)
        }
    }

    fun deleteById(id: E): Boolean {
        return try {
            dao.deleteByKey(id)
            true
        } catch (e: Exception) {
            false
        }
    }

    fun clear(): Boolean {
        return try {
            dao.deleteAll()
            true
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 事务操作
     */
    fun callInTx(call: (DaoSession) -> Boolean): Boolean {
        return daoSession.callInTx {
            call(daoSession)
        }
    }

}